import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 仓库数据接口
export interface Warehouse {
  id: number;
  name: string;
  createTime: string;
}

// 仓库表单字段配置
export const warehouseFields = [
  {
    key: 'name',
    label: '仓库名称',
    type: 'text',
    placeholder: '请输入仓库名称',
    maxLength: 50,
  },
];

export const useWarehouseStore = defineStore('warehouse', {
  state: () => ({
    warehouses: [] as Warehouse[],
  }),
  actions: {
    // 获取仓库列表（无分页）
    async fetchWarehouses() {
      try {
        const response = await axios.get('/warehouses');
        if (response.data.code === 200) {
          this.warehouses = response.data.data;
          return this.warehouses;
        }
        throw new Error(response.data.message || '获取仓库列表失败');
      } catch (error) {
        throw new Error('获取仓库列表失败');
      }
    },

    // 创建仓库
    async createWarehouse(data: { name: string }) {
      try {
        const response = await axios.post('/warehouses', data);
        if (response.data.code === 200) {
          // 创建成功后刷新列表
          await this.fetchWarehouses();
          return response.data.data;
        }
        throw new Error(response.data.message || '创建仓库失败');
      } catch (error) {
        throw new Error('创建仓库失败');
      }
    },

    // 更新仓库
    async updateWarehouse(data: Warehouse) {
      try {
        const response = await axios.put('/warehouses', data);
        if (response.data.code === 200) {
          // 更新成功后刷新列表
          await this.fetchWarehouses();
          return response.data.data;
        }
        throw new Error(response.data.message || '更新仓库失败');
      } catch (error) {
        throw new Error('更新仓库失败');
      }
    },

    // 删除仓库
    async deleteWarehouse(id: number) {
      try {
        const response = await axios.delete(`/warehouses/${id}`);
        if (response.data.code === 200) {
          // 删除成功后刷新列表
          await this.fetchWarehouses();
          return response.data.data;
        }
        throw new Error(response.data.message || '删除仓库失败');
      } catch (error) {
        throw new Error('删除仓库失败');
      }
    },
  },
});